import { Component } from "react";
import { Homepage } from "../App";
import TEditor from "./TEditor";
import Tlogin from "./TLogin";
import TManualLoader from "./TManualLoader";

import Tools from "./tools.json";
import TestCodeMirror from "./TestCodeMirror";

const PageTitle = '宝库';

export default
class TToolbox extends Component{
  constructor(props){
    super(props);

    this.state={
      pageName   : 'index',
      tools      : [],    // 工具列表
      selectedIndex : -1 ,   // 选中引值
    }

    this.handleToolChanged = this.handleToolChanged.bind(this);

    this.refresh = this.refresh.bind(this);
  }

  componentDidMount(){
    document.title =  `T+藏宝馆-${PageTitle}`;
    this.refresh();
  }

  handleToolChanged(event){
    const tool = this.state.tools[event.target.id];
    document.title = `T+藏宝馆-${PageTitle}:${tool.toolName}`;

    this.setState({
      pageName : tool.toolId,
    })
  }

  refresh(){
    // 从books.json中读取书籍列表
    let tools = [];
    let selectedIndex = -1;
    for(let id in Tools){
      tools.push(Tools[id]);
    }
    if(tools.length > 0) selectedIndex = 0;

    this.setState({
      tools         : tools,
      selectedIndex : selectedIndex
    })
  }

  // 渲染书籍列表
  _renderBooks(){
    const tools      = this.state.tools;
    // const selectedIndex = this.state.selectedIndex;

    return tools.map((item, key)=>
      <div className="book" key={key}>
        <img src={`/${Homepage}/${item.toolCover}`} 
          alt={`${Homepage}${item.toolCover}`}>
        </img>
        <button id={key} onClick={this.handleToolChanged}>{item.toolName}</button>
      </div>
    );
  }

  // 显示主页
  homepage(){
    document.title =  `T+藏宝馆-${PageTitle}`;
    this.refresh();

    this.setState({ pageName:'index' });
  }

  _home(){
    return(
    <div className="body">
      <div>
        <button className='hlink' onClick={this.props.home}>T<sup>+</sup>藏宝馆:</button>
        <button className='hlink' onClick={this.refresh}>{`${PageTitle}`}</button>
      </div>
      <div className="book-list">
        {this._renderBooks()}
      </div>
      
    </div>
    );
  }

  render(){
    switch(this.state.pageName){
      case 'index'      : return this._home();
      case 'TManuals'   : return <TManualLoader 
        home={this.homepage.bind(this)}
        BaseUrl = {`/${Homepage}/data/doc/`}
        Index={"manuals.json"}
        />;
      // case 'TEditor'    : return <TEditor home={this.homepage.bind(this)}/>;
      case 'TEditor'    : return <Tlogin home={this.homepage.bind(this)}/>;
      case 'TCodeMirror' : return <TestCodeMirror />;
      default           : return this._home();
    }
  }
}